using System;

using System.Reflection;
using UnityEngine;
using System.IO;
using UnityORM;
using System.Collections.Generic;

public static class SqliteInit
{
	public static DBEvolution Evolution;
	
	static bool alreadyInited = false;
	
	public static void InitSqlite(string dataPath){
		
		if(alreadyInited)return;
		alreadyInited = true;
		Evolution = new DBEvolution(Path.Combine(dataPath,"answer.db"));

		Evolution.RecreateTableIfHashDiffers = true;
		

		
//		Evolution.Evolute("XCardDefine",
//			new List<string>(){
//			new SQLMaker().GenerateCreateTableSQL<XCardDefine>(ClassDescRepository.Instance.GetClassDesc<XCardDefine>()) + " "
//		});

		ReflectEntities();
		
	}


	public static void ReflectEntities()
	{
		Assembly asm=Assembly.GetExecutingAssembly();


		SQLMaker sqlMaker = new SQLMaker();
		ClassDescRepository classRep=ClassDescRepository.Instance;



		MethodInfo method = typeof(SQLMaker).GetMethod("GenerateCreateTableSQL");

		MethodInfo cmethod=typeof(ClassDescRepository).GetMethod("MyGetClassDesc");

		foreach (var type in asm.GetTypes())
		{
			var attributes=Attribute.GetCustomAttribute(type,typeof(TableAttribute));
			
			if (attributes == null)
				continue;

			MethodInfo method2=method.MakeGenericMethod(type);
			MethodInfo cmethod2=cmethod.MakeGenericMethod(type);
			//UnityEngine.Debug.Log("tableName========:"+type.Name+"    attributes:"+attributes);
			//UnityEngine.Debug.Log("Object 1:"+cmethod.Invoke(classRep,null));

			
			Evolution.Evolute(type.Name,
			                			new List<string>(){
				method2.Invoke(sqlMaker,new object[]{cmethod2.Invoke(classRep,null)})+  " "
			
			});
		}
	}
	
}



